package cc.owoo.godpen.analysis.css;

import cc.owoo.godpen.analysis.html.Element;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 选择器组
 * Created by nimensei
 * 2022-06-01 上午 01:27
 */
public class SelectorGroup extends Selector {
    private final LinkedList<SelectorSingle> selectorSingles = new LinkedList<>();// 选择器列表

    /**
     * 添加选择器
     *
     * @param selectorSingle 选择器
     */
    public void add(SelectorSingle selectorSingle) {
        if (selectorSingle == null)
            return;
        selectorSingles.add(selectorSingle);
    }

    /**
     * 获取单条选择器
     *
     * @param index 选择器下标
     * @return 单条选择器
     */
    public SelectorSingle get(int index) {
        if (index < 0 || index >= selectorSingles.size())
            return null;
        return selectorSingles.get(index);
    }

    /**
     * 返回当前选择器组的数量
     *
     * @return 选择器组的数量
     */
    public int size() {
        return selectorSingles.size();
    }

    @Override
    public void select(Queue<Element> elements) {
        if (selectorSingles.size() == 0)
            return;
        if (selectorSingles.size() == 1) {
            selectorSingles.get(0).select(elements);
            return;
        }
        if (elements == null || elements.size() == 0)
            return;
        HashSet<Element> ans = new HashSet<>();
        int index = elements.size();
        for (SelectorSingle selectorSingle : selectorSingles) {
            Queue<Element> list = --index > 0 ? new LinkedList<>(elements) : elements;
            selectorSingle.select(list);
            if (list.size() == 0)
                continue;
            ans.addAll(list);
            list.clear();
        }
        elements.addAll(ans);
        ans.clear();
    }

    /**
     * 序列化选择器组
     *
     * @param string 序列化字符串
     * @param format 是否格式化代码
     * @return 是否有效的序列化了
     */
    @Override
    public boolean stringify(StringBuilder string, String retract, boolean format) {
        if (string == null)
            return false;
        boolean valid = false;
        for (SelectorSingle selectorSingle : selectorSingles) {
            if (selectorSingle.size() == 0)
                continue;
            if (valid)
                string.append(format ? ",\n" : ",");
            valid = selectorSingle.stringify(string, retract, format) || valid;
        }
        return valid;
    }

    @Override
    public String toString() {
        return stringify();
    }
}
